package cn.tedu.rtc.device.service.impl;

import cn.tedu.rtc.component.websocket.service.IWebSocketMessageService;
import cn.tedu.rtc.device.model.EventsReceiver;
import cn.tedu.rtc.redis.model.UserTypeEnum;
import cn.tedu.rtc.sdk.api.device.AbstractDeviceService;
import cn.tedu.rtc.sdk.mqtt.events.EventsDataRequest;
import cn.tedu.rtc.sdk.mqtt.events.RemoteDebugProgress;
import cn.tedu.rtc.sdk.mqtt.events.TopicEventsRequest;
import cn.tedu.rtc.sdk.mqtt.events.TopicEventsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class SDKDeviceService extends AbstractDeviceService {

    @Autowired
    private IWebSocketMessageService webSocketMessageService;

    @Override
    public TopicEventsResponse remoteDebugProgress(TopicEventsRequest<EventsDataRequest<RemoteDebugProgress>> request, MessageHeaders headers) {
        String sn = request.getGateway();

        EventsReceiver<RemoteDebugProgress> eventsReceiver = new EventsReceiver<RemoteDebugProgress>()
                .setOutput(request.getData().getOutput()).setResult(request.getData().getResult());
        eventsReceiver.setBid(request.getBid());
        eventsReceiver.setSn(sn);

        log.info("SN: {}, {} ===> Control progress: {}", sn, request.getMethod(), eventsReceiver.getOutput().getPercent());

        if (eventsReceiver.getResult() != 0) {
            log.error("SN: {}, {} ===> Error: {}", sn, request.getMethod(), eventsReceiver.getResult());
        }

        // 必须利用websocket客户端传递正确的workspaceId，才能储存session到redis，然后这里的sendBatch才不会报错
        webSocketMessageService.sendBatch("a64f5fb0-86c1-4245-b8a5-988a8fcba0c6", UserTypeEnum.WEB.getVal(),
                request.getMethod(), eventsReceiver);

        return new TopicEventsResponse().setData(0);
    }

}
